using AutoMapper.Internal.Mappers;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using ERP.RBAC;
using Volo.Abp.ObjectMapping;
using ERP.RBAC.Dto;
using System.Linq;

using static Volo.Abp.Identity.IdentityPermissions;
using Volo.Abp;
using Microsoft.Extensions.Logging;

namespace ERP.Web.Controllers
{
    public class RBACController : Controller
    {
        private readonly IRoleServicers _roleServices;
        private readonly IUserServices _userServices;
        private readonly IMenuServices _menuServices;
        private readonly ILoginServices _loginServices;
        private readonly IPermissionServices _permissionServices;
        private readonly IUserRoleServices _userRoleServices;
        private readonly ILogger<RBACController> _logger;

      
        public RBACController(IRoleServicers roleServices, IUserServices userServices, IPermissionServices permissionServices, IMenuServices menuServices, ILoginServices loginServices, IUserRoleServices userRoleServices, ILogger<RBACController> logger)
        {
            _roleServices = roleServices;
            _userServices = userServices;
            _menuServices = menuServices;
            _loginServices = loginServices;
            _permissionServices = permissionServices;
            _userRoleServices = userRoleServices;
            _logger = logger;
        }


        /// <summary>
        /// 处理用户登录
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="captcha">验证码</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Login(string username, string password, string captcha = null)
        {
            try
            {
                Console.WriteLine($"========== 开始处理用户 {username} 的登录（诊断模式） ==========");

                // 1. 验证用户名和密码
                var result = await _loginServices.Login(username, password);
                if (result == null || !result.Any())
                {
                    Console.WriteLine("登录验证失败，用户名或密码错误");
                    return Json(new { code = 1, msg = "登录失败，用户名或密码错误", data = "" });
                }

                // 2. 获取用户信息
                var user = result.First();
                Console.WriteLine($"用户验证成功：ID={user.Id}, 用户名={user.Username}, 姓名={user.UserNickname}");

                // 3. 获取用户角色信息
                Console.WriteLine($"开始获取用户角色信息，用户ID={user.Id}");
                var userRoles = await _roleServices.GetUserRoles(user.Id);
                Console.WriteLine($"获取到用户角色数量：{userRoles?.Count ?? 0}");

                // 4. 处理角色信息
                string roleName = null; // 不设置默认值
                if (userRoles != null && userRoles.Any())
                {
                    roleName = userRoles.First().Rolename;
                    Console.WriteLine($"获取到用户角色名称：{roleName}");
                }
                else
                {
                    Console.WriteLine("警告：未获取到用户角色信息");
                }

                // 5. 构建返回数据
                var responseData = new
                {
                    user.Id,
                    user.Username,
                    user.Password,
                    UserNickname = user.UserNickname ?? username,
                    RoleName = roleName
                };

                Console.WriteLine($"返回前端的数据：ID={responseData.Id}, 用户名={responseData.Username}, 姓名={responseData.UserNickname}, 角色={responseData.RoleName ?? "null"}");
                Console.WriteLine($"========== 登录处理完成 ==========");

                // 6. 返回成功结果
                return Json(new
                {
                    code = 0,
                    msg = "登录成功",
                    data = responseData
                });
            }
            catch (System.Exception ex)
            {
                Console.WriteLine($"登录过程中发生错误: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");

                return Json(new
                {
                    code = 1,
                    msg = ex.Message,
                    data = ""
                });
            }
        }


        /// <summary>
        /// 视图
        /// </summary>
        /// <returns></returns>

        public async Task<IActionResult> RoleViewAsync()
        {
            var allMenus = await _menuServices.ShowMenu();


            // 构建菜单树
            var rootMenus = allMenus.Where(m => m.ParentId == null).ToList();

            foreach (var rootMenu in rootMenus)
            {
                rootMenu.Children = GetChildMenus(allMenus, rootMenu.Id);
            }

            return View(rootMenus);
        }

        /// <summary>
        /// 显示所有角色
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> QueryRole(string rolename)
        {
            var roles = await _roleServices.QueryRole();
            
            // 如果提供了角色名称参数，进行模糊查询过滤
            if (!string.IsNullOrWhiteSpace(rolename))
            {
                roles = roles.Where(r => r.Rolename != null && r.Rolename.Contains(rolename, StringComparison.OrdinalIgnoreCase)).ToList();
            }
            
            return Json(new
            {
                code = 0,
                msg = "",
                count = roles.Count,
                data = roles
            });
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="createRolePerDto"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> AddRole(ERP.RBAC.Roles roles)
        {
            var result = await _roleServices.AddRole(roles);
            return Json(new { success = result > 0, message = result > 0 ? "添加成功" : "添加失败" });
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DelRole(int id)
        {
            await _roleServices.DelRole(id);
            return Json(new { success = true, message = "删除成功" });
        }
        /// <summary>
        /// 回显
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> FullRole(int id)
        {
            var role = await _roleServices.FullRole(id);
            return Json(new { success = true, data = role });
        }





        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="createRolePerDto"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> UpRole(int id, string rolename)
        {
            try
            {
                if (string.IsNullOrEmpty(rolename))
                {
                    return Json(new { success = false, message = "角色名称不能为空" });
                }
                
                // 创建角色对象
                var role = new ERP.RBAC.Roles
                {
                    Rolename = rolename
                };
                
                // 使用反射设置ID
                var idProperty = typeof(ERP.RBAC.Roles).GetProperty("Id");
                if (idProperty != null)
                {
                    idProperty.SetValue(role, id);
                }
                else
                {
                    return Json(new { success = false, message = "无法设置角色ID" });
                }
                
                // 更新角色
                var result = await _roleServices.UpRole(role);
                return Json(new { success = result > 0, message = result > 0 ? "修改成功" : "修改失败" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = "修改失败: " + ex.Message });
            }
        }
  



        /// <summary>
        /// 用户管理
        /// </summary>
        public IActionResult UserView()
        {
            return View();
        }

        /// <summary>
        /// 显示所有用户
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<JsonResult> ShowUser()
        {
            var list = await _userServices.ShowUser();
            return Json(new
            {
                code = 0,
                msg = "",
                count = list.Count,
                data = list
            });
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AddUser([FromBody] UserDTO user)
        {
            try
            {
                if (user == null)
                {
                    return BadRequest(new { message = "请求数据为空" });
                }

                if (!ModelState.IsValid)
                {
                    var errors = ModelState.Values
                        .SelectMany(v => v.Errors)
                        .Select(e => e.ErrorMessage)
                        .ToList();
                    return BadRequest(new { message = "数据验证失败", errors = errors });
                }

                if (string.IsNullOrEmpty(user.Username))
                {
                    return BadRequest(new { message = "用户名不能为空" });
                }

                if (string.IsNullOrEmpty(user.Password))
                {
                    return BadRequest(new { message = "密码不能为空" });
                }

                var result = await _userServices.AddUser(user);
                return Json(new { success = result > 0, message = result > 0 ? "添加成功" : "添加失败" });
            }
            catch (System.Exception ex)
            {
                return BadRequest(new { message = "添加失败: " + ex.Message });
            }
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> DeleteUser([FromForm] int userId)
        {
            try
            {
                if (userId <= 0)
                {
                    return Json(new { success = false, message = "无效的用户ID" });
                }

                var result = await _userServices.DeleteUser(userId);
                return Json(new { success = result > 0, message = result > 0 ? "删除成功" : "删除失败" });
            }
            catch (System.Exception ex)
            {
                return Json(new { success = false, message = "删除失败: " + ex.Message });
            }
        }

        /// <summary>
        /// 获取单个用户
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetUser(int userId)
        {
            var user = await _userServices.GetUser(userId);
            return Json(new { success = true, data = user });
        }

        /// <summary>
        /// 更新用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> UpdateUser([FromBody] UserDTO user)
        {
            try
            {
                if (user == null)
                {
                    return BadRequest(new { message = "请求数据为空" });
                }

                if (!ModelState.IsValid)
                {
                    var errors = ModelState.Values
                        .SelectMany(v => v.Errors)
                        .Select(e => e.ErrorMessage)
                        .ToList();
                    return BadRequest(new { message = "数据验证失败", errors = errors });
                }

                if (user.Id <= 0)
                {
                    return BadRequest(new { message = "用户ID无效" });
                }

                if (string.IsNullOrEmpty(user.Username))
                {
                    return BadRequest(new { message = "用户名不能为空" });
                }

                if (string.IsNullOrEmpty(user.Password))
                {
                    return BadRequest(new { message = "密码不能为空" });
                }

                var result = await _userServices.UpdateUser(user);
                return Json(new { success = result > 0, message = result > 0 ? "修改成功" : "修改失败" });
            }
            catch (System.Exception ex)
            {
                return BadRequest(new { message = "修改失败: " + ex.Message });
            }
        }

        private List<MenuDto> GetChildMenus(List<MenuDto> allMenus, int parentId)
        {
            var childMenus = allMenus.Where(m => m.ParentId == parentId).ToList();

            foreach (var childMenu in childMenus)
            {
                childMenu.Children = GetChildMenus(allMenus, childMenu.Id);
            }
            return childMenus;
        }

        /// <summary>
        /// 获取所有权限
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetAllPermissions()
        {
            try
            {
                var permissions = await _permissionServices.GetAllPermissionsAsync();
                return Json(new { success = true, data = permissions });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = "获取权限列表失败: " + ex.Message });
            }
        }

        /// <summary>
        /// 获取角色权限
        /// </summary>
        /// <param name="roleId">角色ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetRolePermissions(int roleId)
        {
            try
            {
                var permissionIds = await _permissionServices.GetRolePermissionsAsync(roleId);
                return Json(new { success = true, data = permissionIds });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = "获取角色权限失败: " + ex.Message });
            }
        }

        /// <summary>
        /// 保存角色权限
        /// </summary>
        /// <param name="roleId">角色ID</param>
        /// <param name="permissionIds">权限ID列表</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> SaveRolePermissions(int roleId, List<int> permissionIds)
        {
            try
            {
                var result = await _permissionServices.SaveRolePermissionsAsync(roleId, permissionIds);
                return Json(new { success = result, message = result ? "保存成功" : "保存失败" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = "保存角色权限失败: " + ex.Message });
            }
        }

        /// <summary>
        /// 获取用户的角色
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetUserRoles(int userId)
        {
            try
            {
                // 获取所有角色
                var allRoles = await _roleServices.QueryRole();
                if (allRoles == null)
                {
                    return Json(new { success = false, message = "获取角色列表失败" });
                }

                // 获取用户当前的角色
                var userRoles = await _userRoleServices.GetUserRoles(userId);
                
                // 构建返回数据
                var result = allRoles.Select(role => new
                {
                    id = role.Id,
                    rolename = role.Rolename,
                    isChecked = userRoles?.Any(ur => ur.RoleId == role.Id) ?? false
                }).ToList();

                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = "获取角色失败: " + ex.Message });
            }
        }

        /// <summary>
        /// 为用户分配角色
        /// </summary>
        /// <param name="request">角色分配请求</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AssignUserRoles([FromBody] AssignRolesDto request)
        {
            try
            {
                _logger.LogInformation($"收到角色分配请求: UserId={request?.UserId}, RoleIds={request?.RoleIds?.Count ?? 0}个");

                if (request == null)
                {
                    _logger.LogWarning("请求数据为空");
                    return Json(new { success = false, message = "请求数据无效" });
                }

                if (!ModelState.IsValid)
                {
                    var errors = string.Join(", ", ModelState.Values
                        .SelectMany(v => v.Errors)
                        .Select(e => e.ErrorMessage));
                    _logger.LogWarning($"数据验证失败: {errors}");
                    return Json(new { success = false, message = $"数据验证失败: {errors}" });
                }

                if (request.UserId <= 0)
                {
                    _logger.LogWarning($"无效的用户ID: {request.UserId}");
                    return Json(new { success = false, message = "用户ID无效" });
                }

                if (request.RoleIds == null || !request.RoleIds.Any())
                {
                    _logger.LogWarning($"用户 {request.UserId} 的角色列表为空");
                    return Json(new { success = false, message = "请至少选择一个角色" });
                }

                // 验证角色是否存在
                var allRoles = await _roleServices.QueryRole();
                if (allRoles == null)
                {
                    _logger.LogError("获取角色列表失败");
                    return Json(new { success = false, message = "获取角色列表失败" });
                }

                var invalidRoles = request.RoleIds.Except(allRoles.Select(r => r.Id)).ToList();
                if (invalidRoles.Any())
                {
                    _logger.LogWarning($"发现无效的角色ID: {string.Join(", ", invalidRoles)}");
                    return Json(new { success = false, message = $"包含无效的角色ID: {string.Join(", ", invalidRoles)}" });
                }

                // 保存角色分配
                _logger.LogInformation($"开始为用户 {request.UserId} 分配 {request.RoleIds.Count} 个角色");
                await _userRoleServices.AssignUserRoles(request.UserId, request.RoleIds);
                _logger.LogInformation($"用户 {request.UserId} 的角色分配成功");
                
                return Json(new { success = true, message = "角色分配成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"角色分配过程中发生错误: {ex.Message}");
                return Json(new { success = false, message = $"角色分配失败: {ex.Message}" });
            }
        }
    }
}
